package com.example.concurrent.demo.aqs;

import java.util.Date;
import java.util.concurrent.*;

/**
 * @author susc
 * @title: CountDownLatchExample1
 * @projectName concurrent-demo
 * @description: 场景：我们要读取处理 6 个文件，这 6 个任务都是没有执行顺序依赖的任务，但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。
 * @date 2021/9/2816:04
 */
public class CountDownLatchExample1 {
    // 处理文件的数量
    private static final int threadCount = 6;
    // 核心线程数
    private static int CORE_POOL_SIZE = 6;
    // 最大线程数
    private static int MAX_POOL_SIZE = 10;
    // 等待队列长度
    private static int QUEUE_CAPACITY = 6;
    // 生存时间
    private static Long KEEP_ALIVE_TIME = 1L;

    public static void main(String[] args) throws InterruptedException {
        // 创建一个具有固定线程数量的线程池对象（)
        ExecutorService threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY));
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for(int i = 0; i< threadCount; i++){
            final int threadnum = i;
            threadPool.execute(
                    ()-> {
                            // 处理文件的业务操作
                            try {
                                Thread.sleep(6000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                // 表示一个文件已被完成
                                countDownLatch.countDown();
                                System.out.println(  new Date() + ":文件" + threadnum + "，已完成操作!");
                            }

                    }
            );
        }

        countDownLatch.await();
        threadPool.shutdown();
        System.out.println("all finish!");

    }
}
